package com.ztom.daily.n2022.m5;

import java.util.Arrays;

/**
 * 重新排列日志文件
 * <p>
 * https://leetcode-cn.com/problems/reorder-data-in-log-files/
 *
 * @author ZhangTao
 */
public class Day03ReorderLogFiles {

    public static class Log implements Comparable<Log>{

        private String content;
        // 数字要求保留原顺序
        private int index;
        private String prefix;
        private String suffix;
        // 字母=0; 数字=1
        private int type;

        public Log(String log, int index) {
            this.content = log;
            this.index = index;
            String[] split = log.split(" ", 2);
            this.prefix = split[0];
            this.suffix = split[1];
            this.type = Character.isDigit(this.suffix.charAt(0)) ? 1 : 0;
        }

        @Override
        public int compareTo(Log b) {
            // 都是数字要求保留原顺序
            if (this.type == 1 && b.type == 1) {
                return this.index - b.index;
            }

            // 都是字母
            if (this.type == 0 && b.type == 0) {
                int compare = this.suffix.compareTo(b.suffix);
                if (compare == 0) {
                    // 相等 则按标识符
                    return this.prefix.compareTo(b.prefix);
                }
                return compare;
            }

            // 字母排在数字前
            return this.type == 1 ? 1 : -1;
        }
    }

    public String[] reorderLogFiles(String[] logs) {
        if (logs == null || logs.length == 0) {
            return new String[]{};
        }
        int n = logs.length;
        Log[] arr = new Log[n];
        for (int i = 0; i < logs.length; i++) {
            arr[i] = new Log(logs[i], i);
        }
        Arrays.sort(arr);
        String[] res = new String[n];
        for (int i = 0; i < n; i++) {
            res[i] = arr[i].content;
        }
        return res;
    }
}
